from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.generics import ListAPIView, CreateAPIView, ListCreateAPIView, UpdateAPIView
from rest_framework.views import APIView

# Create your views here.
from rest_framework_extensions.cache.decorators import cache_response
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from areas.serializers import AreasSerializer, AddressesSerializer
from users.models import Address


class AreasView(CacheResponseMixin, ListAPIView):
    """
        获取省的信息
    """
    serializer_class = AreasSerializer
    queryset = Area.objects.filter(parent=None)


class AreaView(CacheResponseMixin, ListAPIView):
    """
        获取市的信息和区县信息获取

    """
    serializer_class = AreasSerializer

    # queryset = Area.objects.filter(parent_id=pk)

    # 父类方法不满足需求，子类重写方法
    # @cache_response(timeout=60 * 60, cache='default')
    def get_queryset(self):
        pk = self.kwargs['pk']
        return Area.objects.filter(parent_id=pk)


class AddressesView(ListCreateAPIView, UpdateAPIView):
    """
        保存收货地址
        获取收货地址
        更新收货地址
    """
    serializer_class = AddressesSerializer

    queryset = Address.objects.all()

    # def get_serializer_class(self):
    #     if self.request.method == "GET":
    #         return AddressSerialzier
    #     elif self.request.method == "POST":
    #         return AddressesSerializer
    # #
    # def get_queryset(self):
    #     address=Address.objects.filter(user=self.request.user)
    #     default_address_id=self.request.user.default_address_id
    #     query_set={'addresses':address,'default_address_id':default_address_id}
    #     return query_set
    # #
    # def get_serializer(self, *args, **kwargs):
    #     """
    #     Return the serializer instance that should be used for validating and
    #     deserializing input, and for serializing output.
    #     """
    #     serializer_class = self.get_serializer_class()
    #     kwargs['context'] = self.get_serializer_context()
    #
    #     if self.request.method=="GET":
    #         del kwargs['many']
    #     return serializer_class(*args, **kwargs)

    # def list(self, request, *args, **kwargs):
    #     queryset = self.filter_queryset(self.get_queryset())
    #
    #     page = self.paginate_queryset(queryset)
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True)
    #         return self.get_paginated_response(serializer.data)
    #
    #     serializer = self.get_serializer(queryset)
    #
    #     return Response(serializer.data)

    def get(self, request, *args, **kwargs):
        # 获取用户
        user = request.user

        # 查询地址
        address = Address.objects.filter(user=user, is_deleted=False)
        # 插叙默认地址
        default_address_id = user.default_address_id
        if default_address_id is None:
            default_address_id = 'False'
        # 序列化地址对象
        ser = self.get_serializer(address, many=True)

        addresses = ser.data

        return Response({'addresses': addresses, 'default_address_id': default_address_id})

    def delete(self, request, pk):
        try:
            address = Address.objects.get(id=pk)
        except:
            return Response({'error': '错误id值'}, status=400)
        # 逻辑删除
        address.is_deleted = True
        address.save()

        return Response()


class DefaultAddresView(APIView):
    """
        设置默认地址
    """

    def put(self, request, pk):
        # 1、获取id和用户对象
        user = request.user
        # 2、验证数据 查询id所对应的地址是否存在
        try:
            Address.objects.get(id=pk)
        except:
            return Response(status=400)
        # 3、更新新数据
        user.default_address_id = pk
        user.save()
        # 4、返回结果
        return Response({"default_address_id": user.default_address_id})
